<template>
  <div class="navbar">
    <div class="navbar-content">
      <!-- Logo -->
      <div class="logo" @click="router.push('/')">
        <img src="../assets/logo.png" alt="Logo">
        <span>在线教育平台</span>
      </div>

      <!-- 导航菜单 -->
      <div class="nav-menu">
        <el-menu
          mode="horizontal"
          :router="true"
          :default-active="activeMenu"
        >
          <el-menu-item index="/home">首页</el-menu-item>
          <el-sub-menu index="/course">
            <template #title>课程中心</template>
            <el-menu-item index="/course/list">全部课程</el-menu-item>
          </el-sub-menu>
          <el-menu-item index="/news">最新动态</el-menu-item>
          <el-sub-menu index="/teacher">
            <template #title>讲师团队</template>
            <el-menu-item index="/teacher">全部讲师</el-menu-item>
          </el-sub-menu>
        </el-menu>
      </div>

      <!-- 用户菜单 -->
      <div class="user-menu">
        <template v-if="isLoggedIn">
          <el-dropdown trigger="click">
            <div class="user-info">
              <el-avatar :size="32" :src="userAvatar" />
              <span class="username">{{ username }}</span>
            </div>
            <template #dropdown>
              <el-dropdown-menu>
                <el-dropdown-item @click="handleUserAction('/user/profile')">
                  <el-icon><User /></el-icon>个人中心
                </el-dropdown-item>
                <template v-if="!isAdmin">
                  <el-dropdown-item @click="handleUserAction('/user/courses')">
                    <el-icon><Reading /></el-icon>我的课程
                  </el-dropdown-item>
                  <el-dropdown-item @click="handleUserAction('/user/favorites')">
                    <el-icon><Star /></el-icon>我的收藏
                  </el-dropdown-item>
                </template>
                <el-dropdown-item divided @click="handleLogout">
                  <el-icon><SwitchButton /></el-icon>退出登录
                </el-dropdown-item>
              </el-dropdown-menu>
            </template>
          </el-dropdown>
        </template>
        <template v-else>
          <el-button type="primary" @click="showLoginDialog">登录</el-button>
          <el-button type="info" @click="showRegisterDialog">注册</el-button>
        </template>
      </div>
    </div>

    <!-- 登录对话框 -->
    <el-dialog
      v-model="loginDialogVisible"
      title="用户登录"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="loginForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="loginForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="loginDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleLogin">登录</el-button>
        </span>
      </template>
    </el-dialog>

    <!-- 注册对话框 -->
    <el-dialog
      v-model="registerDialogVisible"
      title="用户注册"
      width="400px"
      :close-on-click-modal="false"
    >
      <el-form
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        label-width="80px"
      >
        <el-form-item label="用户名" prop="username">
          <el-input v-model="registerForm.username" placeholder="请输入用户名" />
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            v-model="registerForm.password"
            type="password"
            placeholder="请输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="请再次输入密码"
            show-password
          />
        </el-form-item>
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="registerForm.email" placeholder="请输入邮箱" />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="registerDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleRegister">注册</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { ElMessage } from 'element-plus'
import { 
  User, Reading, Star, Setting, SwitchButton
} from '@element-plus/icons-vue'

const router = useRouter()
const route = useRoute()

// 登录状态
const isLoggedIn = ref(false)
const username = computed(() => {
  const userInfo = localStorage.getItem('userInfo');
  if (userInfo) {
    try {
      const parsedUserInfo = JSON.parse(userInfo);
      // 修改这里的逻辑：如果是管理员，则直接返回用户名
      if (isAdmin.value) {
        return parsedUserInfo.username || '';
      } else {
        // 否则，优先返回真实姓名，如果真实姓名不存在或为空，则返回用户名
        return parsedUserInfo.realName || parsedUserInfo.username || '';
      }
    } catch (e) {
      console.error('Failed to parse userInfo from localStorage', e);
      return '';
    }
  }
  return '';
});
const userAvatar = ref('')
const isAdmin = ref(false)

// 登录对话框
const loginDialogVisible = ref(false)
const loginFormRef = ref(null)
const loginForm = ref({
  username: '',
  password: ''
})

// 表单验证规则
const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ]
}

// 注册对话框
const registerDialogVisible = ref(false)
const registerFormRef = ref(null)
const registerForm = ref({
  username: '',
  password: '',
  confirmPassword: '',
  email: ''
})

// 注册表单验证规则
const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 20, message: '长度在 3 到 20 个字符', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '长度在 6 到 20 个字符', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.value.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ],
  email: [
    { required: true, message: '请输入邮箱地址', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ]
}

// 当前激活的菜单项
const activeMenu = computed(() => {
  const path = route.path
  if (path.startsWith('/category')) return 'course'
  return path
})

// 显示登录对话框
function showLoginDialog() {
  loginDialogVisible.value = true
}

// 显示注册对话框
function showRegisterDialog() {
  registerDialogVisible.value = true
}

// 处理登录
const handleLogin = async () => {
  if (!loginFormRef.value) return
  
  try {
    await loginFormRef.value.validate()
    
    // 验证用户名和密码
    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
    const user = registeredUsers.find(u => u.username === loginForm.value.username && u.password === loginForm.value.password)
    
    if (user) {
      // 普通用户登录
      const userInfo = {
        username: user.username,
        email: user.email,
        role: 'user',
        avatar: user.avatar || ''
      }
      // 清除旧的用户会话信息，保留 registeredUsers
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('role');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('isAdmin');
      localStorage.removeItem('avatar');
      
      // 保存新的用户信息
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('isAdmin', 'false')
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      // localStorage.setItem('avatar', userInfo.avatar) // 如果需要保存用户头像到单独的key

      ElMessage.success('登录成功')
      router.push('/user/profile')
    } else if (loginForm.value.username === 'admin' && loginForm.value.password === 'admin123456') {
      // 管理员登录
      const userInfo = {
        username: 'admin',
        realName: '管理员', // 添加管理员真实姓名
        email: 'admin@example.com',
        role: 'admin',
        avatar: 'https://picsum.photos/200/200?random=1' // 管理员头像示例
      }
      // 清除旧的用户会话信息，保留 registeredUsers
      localStorage.removeItem('isLoggedIn');
      localStorage.removeItem('role');
      localStorage.removeItem('userInfo');
      localStorage.removeItem('isAdmin');
      localStorage.removeItem('avatar');

      // 保存新的用户信息
      localStorage.setItem('isLoggedIn', 'true')
      localStorage.setItem('role', 'admin')
      localStorage.setItem('isAdmin', 'true')
      localStorage.setItem('userInfo', JSON.stringify(userInfo))
      // localStorage.setItem('avatar', userInfo.avatar) // 如果需要保存用户头像到单独的key

      ElMessage.success('管理员登录成功')
      router.push('/admin/profile')
    } else {
      ElMessage.error('用户名或密码错误')
      return
    }
    
    loginDialogVisible.value = false
    
    // 清空表单
    loginForm.value = {
      username: '',
      password: ''
    }
  } catch (error) {
    ElMessage.error('请检查输入信息')
  }
}

// 处理注册
async function handleRegister() {
  if (!registerFormRef.value) return
  
  try {
    await registerFormRef.value.validate()
    
    // 检查用户名是否已存在
    const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers') || '[]')
    if (registeredUsers.some(user => user.username === registerForm.value.username)) {
      ElMessage.error('用户名已存在')
      return
    }
    
    // 创建新用户
    const newUser = {
      username: registerForm.value.username,
      password: registerForm.value.password,
      email: registerForm.value.email,
      registerTime: new Date().toISOString(),
      avatar: ''
    }
    
    // 保存用户信息到 localStorage
    registeredUsers.push(newUser)
    localStorage.setItem('registeredUsers', JSON.stringify(registeredUsers))
    
    ElMessage.success('注册成功，请登录')
    registerDialogVisible.value = false
    
    // 注册成功后，自动填充登录表单并显示登录对话框
    loginForm.value.username = newUser.username;
    loginForm.value.password = newUser.password;
    showLoginDialog();

  } catch (error) {
    console.error('注册失败:', error);
    ElMessage.error('注册失败，请检查填写的信息')
  }
}

// 处理用户操作
function handleUserAction(path) {
  if (!isLoggedIn.value) {
    showLoginDialog()
    return
  }
  // 根据isAdmin判断跳转路径
  const targetPath = path === '/user/profile' && isAdmin.value ? '/admin/profile' : path;
  router.push(targetPath)
}

// 处理退出登录
function handleLogout() {
  isLoggedIn.value = false
  isAdmin.value = false
  userAvatar.value = ''
  
  // 清除登录状态
  localStorage.removeItem('isLoggedIn')
  localStorage.removeItem('role')
  localStorage.removeItem('userInfo'); // 退出时清除用户信息
  
  ElMessage.success('已退出登录')
  router.push('/home')
}

// 检查登录状态
function checkLoginStatus() {
  const storedLoginStatus = localStorage.getItem('isLoggedIn')
  const storedRole = localStorage.getItem('role')
  
  if (storedLoginStatus === 'true') {
    isLoggedIn.value = true
    isAdmin.value = storedRole === 'admin'
    userAvatar.value = isAdmin.value ?
      'https://picsum.photos/200/200?random=1' :
      'https://picsum.photos/200/200?random=2'
  }
}

// 初始化时检查登录状态
checkLoginStatus()

// 处理路由跳转
function goToCategory(categoryId) {
  router.push(`/category/${categoryId}`)
}
</script>

<style scoped>
.navbar {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  height: 64px;
  background: white;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  z-index: 1000;
}

.navbar-content {
  max-width: 1200px;
  height: 100%;
  margin: 0 auto;
  padding: 0 20px;
  display: flex;
  align-items: center;
  justify-content: space-between;
}

.logo {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.logo img {
  height: 32px;
}

.logo span {
  font-size: 18px;
  font-weight: bold;
  color: var(--text-primary);
}

.nav-menu {
  flex: 1;
  margin: 0 40px;
}

.nav-menu :deep(.el-menu) {
  border: none;
}

.nav-menu :deep(.el-menu-item) {
  font-size: 16px;
}

.user-menu {
  display: flex;
  align-items: center;
  gap: 12px;
}

.user-info {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
}

.username {
  font-size: 14px;
  color: var(--text-primary);
}

:deep(.el-dropdown-menu__item) {
  display: flex;
  align-items: center;
  gap: 8px;
}

:deep(.el-dropdown-menu__item .el-icon) {
  margin-right: 4px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}
</style> 